#include <iostream>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>

void mycleanfunc(void *arg)
{
    printf("my clean func:%d\n", *((int *)arg));
}

void *thfunc(void *arg)
{
    int i = 1;
    printf("thread start \n");
    pthread_cleanup_push(mycleanfunc, &i);
    while (1)
    {
        i++;
        printf("i=%d\n", i);
    }
    printf("this line not run");
    pthread_cleanup_pop(0);
    return (void *)0;
}

int main()
{
    void *ret = NULL;
    int iret = 0;
    pthread_t tid;
    pthread_create(&tid, NULL, thfunc, NULL);
    sleep(1);
    pthread_cancel(tid);
    pthread_join(tid, &ret);
    if (ret == PTHREAD_CANCELED)
    {
        printf("thread stopped,exitcode : %d\n", ret);// should be -1
    }
    else
    {
        printf("error occured");
    }

    return 0;
}